package com.juphoon.oauth.oauth.store;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;

/**
 * @author rongbin.huang
 * oauth2 token存储方式 配置文件中 juphoon.security.oauth.storeType = redis/jwt 默认jwt
 */
@Configuration
public class TokenStoreConfig {


    public static final String SIGN_KEY = "juphoon";

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Autowired(required = false)
    private DataSource dataSource;

    @Bean
    @ConditionalOnProperty(prefix = "com.juphoon.security.oauth2", name = "storeType", havingValue = "redis")
    public TokenStore redisTokenStore() {
        return new JRedisTokenStore(redisConnectionFactory);
    }


    @Bean
    @ConditionalOnProperty(prefix = "com.juphoon.security", name = "clientDb", havingValue = "jdbc")
    public ClientDetailsService clientDetailsService() {
        return new JdbcClientDetailsService(dataSource);
    }

    /**
     * 默认使用jwt
     */
    @Configuration
    @ConditionalOnProperty(prefix = "com.juphoon.security.oauth2", name = "storeType", havingValue = "jwt", matchIfMissing = true)
    public static class JwtTokenConfig {

        @Bean
        public TokenStore jwtTokenStore() {
            return new JwtTokenStore(jwtAccessTokenConverter());
        }


        @Bean
        public JwtAccessTokenConverter jwtAccessTokenConverter() {
            JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
            accessTokenConverter.setSigningKey(SIGN_KEY);
            return accessTokenConverter;

        }


    }

}
